#!/usr/bin/env python
from standard_script_setup import *
from CIME.utils import run_bld_cmd_ensure_logging
from CIME.case import Case
from CIME.build import get_standard_makefile_args

logger = logging.getLogger(__name__)

def parse_command_line(args, description):
###############################################################################
    parser = argparse.ArgumentParser(
        usage="""\n{0} [--debug]
OR
{0} --verbose
OR
{0} --help

\033[1mEXAMPLES:\033[0m
    \033[1;32m# Run \033[0m
    > {0}
""" .format (os.path.basename(args[0])),

description=description,

formatter_class=argparse.ArgumentDefaultsHelpFormatter
)

    CIME.utils.setup_standard_logging_options(parser)

    parser.add_argument("buildroot",
                        help="build path root")

    parser.add_argument("installpath",
                        help="install path ")

    parser.add_argument("caseroot", nargs="?", default=os.getcwd(),
                        help="Case directory to build")

    args = CIME.utils.parse_args_and_handle_standard_logging_options(args, parser)

    return args.buildroot, args.installpath, args.caseroot

def buildlib(bldroot, installpath, case):
###############################################################################
    caseroot = case.get_value("CASEROOT")
    gptl_dir = os.path.join(case.get_value("CIMEROOT"), "src", "share", "timing")
    gmake_opts = "-f {gptl}/Makefile install -C {bldroot} MACFILE={macfile} MODEL=gptl COMP_NAME=gptl GPTL_DIR={gptl} GPTL_LIBDIR={bldroot}"\
        " SHAREDPATH={install} {stdargs} "\
        .format(gptl=gptl_dir, bldroot=bldroot, macfile=os.path.join(caseroot,"Macros.make"),
                install=installpath, stdargs=get_standard_makefile_args(case, shared_lib=True))

    gmake_cmd = case.get_value("GMAKE")

    # This runs the gptl make command
    cmd = "{} {}".format(gmake_cmd, gmake_opts)
    run_bld_cmd_ensure_logging(cmd, logger)

def _main(argv, documentation):
    bldroot, installpath, caseroot = parse_command_line(argv, documentation)
    with Case(caseroot) as case:
        buildlib(bldroot, installpath, case)

if (__name__ == "__main__"):
    _main(sys.argv, __doc__)
